package com.pig4cloud.pigx.wallet.api.v1.utils;

import com.pig4cloud.pigx.common.customize.api.enums.AbnormalEnum;
import com.pig4cloud.pigx.common.customize.api.util.OpenApiUtil;
import com.pig4cloud.pigx.common.customize.contants.MongoTableNameConstants;
import com.pig4cloud.pigx.common.customize.enums.CommonDictEnum;
import com.pig4cloud.pigx.common.customize.security.utils.SecurityUtil;
import com.pig4cloud.pigx.common.security.service.PigxUser;
import com.pig4cloud.pigx.contract.mongo.entity.ContractSymbolMongo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

/**
 */
@Slf4j
@Component
@AllArgsConstructor
public class WalletUtilsV1 {

	private final MongoTemplate mongo;

	/**
	 * 获取币对
	 *
	 * @param symbolName 币对名称
	 * @return mongo
	 */
	public ContractSymbolMongo getSymbolMongo(String symbolName) {
		ContractSymbolMongo mongoOne;
		try {
			mongoOne = mongo.findOne(
					Query.query(Criteria.where("name").is(symbolName)),
					ContractSymbolMongo.class,
					MongoTableNameConstants.CONTRACT_SYMBOL
			);
		} catch (Exception e) {
			// mongo异常 服务器错误
			throw OpenApiUtil.getError(AbnormalEnum.MSG.DISCONNECTED);
		}
		// 无效的币对
		if (mongoOne == null) {
			throw OpenApiUtil.getError(AbnormalEnum.MSG.BAD_SYMBOL);
		}
		// 币对已过期
		if (mongoOne.getStatus().equals(CommonDictEnum.Status.DEPRECATED.getValue())) {
			throw OpenApiUtil.getError(AbnormalEnum.MSG.SYMBOL_ALREADY_CLOSED);
		}
		return mongoOne;
	}

	/**
	 * 获取用户
	 *
	 * @return user
	 */
	public PigxUser getUser() {
		// 获取用户信息
		PigxUser user = SecurityUtil.getLoginUserNotNull();
		if (user == null || user.getId() == null) {
			throw OpenApiUtil.getError(AbnormalEnum.MSG.OPTIONS_USER_NOT_FOUND);
		}
		return user;
	}

}
